const util = require('util')
    , rawBody = require('raw-body')
    , contentType = require('content-type')
    , parseString = util.promisify(require('xml2js').parseString)

let getRawBody = async function(ctx){
    return await rawBody(ctx.req, {
        length: ctx.req.headers['content-length'],
        limit: '1mb',
        encoding: contentType.parse(ctx.req).parameters.charset
    })
}
let xml2json = async function(content){
    return parseString(content, {explicitArray: false})
}

const buildMsg = function (opt) {
    return `<xml>
<ToUserName><![CDATA[${opt.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[${opt.ToUserName}]]></FromUserName>
<CreateTime>${parseInt(new Date().valueOf() / 1000)}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${opt.Content}]]></Content>
</xml>`
}





module.exports = {
    getRawBody: getRawBody,
    xml2json: xml2json,
    buildMsg: buildMsg
}
